<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import type { SearchEmpModel, EmpExprModel, EmpModel, EmpModelArray, DeptModelArray, LoginInfo } from '@/api/model/model'
import axios from 'axios'
import { queryEmp, addEmp, getEmpById, updateEmp, deleteEmpByIds } from '@/api/emp/index'
import { queryDeptList } from '@/api/dept/index'
import type { UploadProps, FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// 获取token
import { useLoginEmpStore } from '@/stores/loginEmp'
const loginEmpStore = useLoginEmpStore();
const loginInfo = ref<LoginInfo>(loginEmpStore.getLoginInfo());

// 页面顶部的搜索
const searchForm = ref<SearchEmpModel>({
    name: '',
    gender: '',
    date: [],
    begin: '',
    end: ''
})

onMounted(() => {
    // 查询员工列表
    query();
    // 查询所有的部门，给弹框中的部门下拉列表用
    queryDepts();
});

const query = async () => {
    // console.log("query param:", searchForm.value);
    const res = await queryEmp(searchForm.value.name, searchForm.value.gender, searchForm.value.begin, searchForm.value.end, currentPage.value, pageSize.value);
    empList.value = res.data.rows
    total.value = res.data.total
}

const queryDepts = async () => {
    const res = await queryDeptList();
    deptList.value = res.data;
}

const jobList = [{ id: 1, name: "班主任" }, { id: 2, name: "讲师" }, { id: 3, name: "学工主管" }, { id: 4, name: "教研主管" }, { id: 5, name: "咨询师" }]

const clear = () => {
    searchForm.value = { name: '', gender: '', date: [], begin: '', end: '' }
}

// 把日期选择框中的2个日期赋值给begin和end，方便使用
watch(() => searchForm.value.date, (newValue, oldValue) => {
    // console.log(newValue);
    if (newValue && newValue.length > 0) {
        searchForm.value.begin = newValue[0];
        searchForm.value.end = newValue[1];
    } else {
        searchForm.value.begin = '';
        searchForm.value.end = '';
    }
});

// 页面主体的数据列表
const empList = ref<EmpModelArray>();
// 分页的数据
let currentPage = ref<number>(1)
const pageSize = ref<number>(5);
const total = ref<number>(0);
const handleSizeChange = () => {
    currentPage = ref<number>(1);
    query();
}
const handleCurrentChange = () => {
    query();
}
// dialog弹框
const dialogFormVisible = ref<boolean>(false)
const deptList = ref<DeptModelArray>()
const dialogTitle = ref<string>('')
const insertOrUpdateForm = ref<EmpModel>({
    username: '',
    name: '',
    gender: '',
    phone: '',
    salary: '',
    entryDate: '',
    deptId: '',
    job: '',
    exprList: []
});
const formLabelWidth = "80px";
// 新增
const openAddDialog = () => {
    dialogFormVisible.value = true;
    dialogTitle.value = "新增员工";
}

// 更新
const handleEdit = async (idx: number, row: EmpModel) => {
    if (!row.id) {
        return;
    }
    // 展示弹框
    dialogFormVisible.value = true;
    dialogTitle.value = "修改员工";
    // 回显查询，参数是id
    const res = await getEmpById(row.id);
    insertOrUpdateForm.value = res.data;
    // 数据类型不一致导致select无法选中
    insertOrUpdateForm.value.gender = '' + insertOrUpdateForm.value.gender
    console.log(insertOrUpdateForm.value);
    // 特殊处理一下工作经历中的时间
    const exprList = insertOrUpdateForm.value.exprList;
    if (!exprList || exprList.length <= 0) {
        return;
    }
    exprList.forEach((expr) => {
        expr.exprDate = [expr.begin, expr.end]
    });
}

const insertOrUpdate = (formEL: FormInstance | undefined) => {
    // console.log("insertOrUpdate");
    if (!formEL) {
        return;
    }
    // 先校验表单的格式
    formEL.validate(async (valid) => {
        if (valid) {
            // 校验通过
            let res = null;
            let insertFlag = null;
            if (insertOrUpdateForm.value.id) {//修改
                insertFlag = false;
                res = await updateEmp(insertOrUpdateForm.value);
            } else {// 新增
                insertFlag = true;
                res = await addEmp(insertOrUpdateForm.value);
            }
            if (!res.code) {
                ElMessage.error(res.msg);
            } else {
                // 隐藏dialog
                dialogFormVisible.value = false;
                // 清空dialog，通过dialog的回调统一处理
                ElMessage({ type: 'success', message: insertFlag ? '添加成功' : '修改成功', })
                query();
            }
        }
    });

}

const handleDelete = (idx: number, row: EmpModel) => {
    ElMessageBox.confirm('您确认删除此数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            const res = await deleteEmpByIds('' + row.id);
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg, })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();
            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}
// 保存所有选中的行的id
const selectIds = ref<(number | undefined)[]>([])
// 入参：是所有的选中的行的数据的数组
const handleSelectionChange = (rows: EmpModelArray) => {
    // 重置selectIds
    selectIds.value = []
    if (!selectIds) {
        return;
    }
    if (!rows || rows.length <= 0) {
        selectIds.value = []
    } else {
        for (let i = 0; i < rows.length; i++) {
            selectIds.value.push(rows[i].id);
        }
        // 或者：
        //selectIds.value = rows.map(row=>row.id);
    }
}
const batchDelete = () => {
    // 先判断seleectIds是否有值
    if (!selectIds.value || selectIds.value.length <= 0) {
        ElMessage({ type: 'error', message: '没有选中任何数据' })
        return;
    }
    ElMessageBox.confirm('您确认删除这些数据吗?', '确认删除', { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning', })
        .then(async () => {
            // 发删除请求
            // 数组元素拼接：selectIds.value.join(",")
            const res = await deleteEmpByIds(selectIds.value.join(","));
            if (!res.code) {
                ElMessage({ type: 'error', message: res.msg, })
            } else {
                ElMessage({ type: 'success', message: '删除成功' })
                // 刷新页面
                query();

            }
        }).catch(() => {
            ElMessage({ type: 'info', message: '取消删除' })
        })
}

// 文件上传
// 上传成功以后的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    // 解析服务端返回的url地址
    insertOrUpdateForm.value.image = response.data;
}
// 上传之前的校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
        ElMessage.error('文件类型必须是jpg或者jpeg或者png')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('文件大小不能超过2MB!')
        return false
    }
    return true
}
//  工作经历
const addExpr = () => {
    // console.log("添加工作经历");
    insertOrUpdateForm.value.exprList.push({
        exprDate: [],
        begin: '',
        end: '',
        company: '',
        job: ''
    });
}
const deleteExpr = (expr: EmpExprModel) => {
    if (!insertOrUpdateForm) {
        return;
    }
    let exprList = insertOrUpdateForm.value.exprList
    if (!exprList || exprList.length <= 0) {
        return;
    }
    // 找expr在列表中的索引
    let pos = exprList.indexOf(expr);
    if (pos < 0) {
        return;
    }
    // 按索引来删除1个元素
    exprList.splice(pos, 1)
}
watch(insertOrUpdateForm, (newValue, oldValue) => {
    let exprList = newValue.exprList;
    if (!exprList || exprList.length <= 0) {
        return;
    }
    for (let i = 0; i < exprList.length; i++) {
        let expr = exprList[i];
        if (!expr.exprDate || expr.exprDate.length <= 0) {
            expr.begin = '';
            expr.end = '';
        } else {
            expr.begin = expr.exprDate[0];
            expr.end = expr.exprDate[1];
        }
    }
    // console.log("exprList", exprList);
}, { deep: true });
// 表单校验
const rules = ref<FormRules<EmpModel>>({
    username: [
        { required: true, message: '用户名不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '用户名长度在2-10个字之间', trigger: 'blur' },
    ],
    name: [
        { required: true, message: '用户姓名不能为空', trigger: 'blur' },
        { min: 2, max: 10, message: '用户姓名长度在2-10个字之间', trigger: 'blur' },
    ],
    gender: [
        { required: true, message: '性别不能为空', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        { pattern: /^1[3-9][0-9]{9}$/, message: '手机号格式有误', trigger: 'blur' },
    ],
    salary: [
        { pattern: /^[1-9]\d*$/, message: '薪水格式有误', trigger: 'blur' },
    ],
})
const dialogFromRef = ref<FormInstance>();



// dialog关闭的时候自动回调
function dialogClose() {
    if (!dialogFromRef || !dialogFromRef.value) {
        return;
    }
    insertOrUpdateForm.value =
    {
        username: '',
        name: '',
        gender: '',
        phone: '',
        salary: '',
        entryDate: '',
        deptId: '',
        job: '',
        exprList: []
    }
    // 重置form校验规则
    dialogFromRef.value.resetFields();
}


</script>
<template>
    <span class="title">员工管理 </span>

    <!----------------------------------搜索框-------------------------------------->
    <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入员工姓名" style="width:200px" clearable />
        </el-form-item>
        <el-form-item label="性别">
            <el-select v-model="searchForm.gender" placeholder="请选择" style="width:200px" clearable>
                <el-option label="男" value="1" />
                <el-option label="女" value="2" />
                <el-option label="其他" value="3" />
            </el-select>
        </el-form-item>
        <el-form-item label="入职时间">
            <el-date-picker v-model="searchForm.date" value-format="YYYY-MM-DD" type="daterange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>
            <el-button type="info" @click="clear">清空</el-button>
        </el-form-item>
    </el-form>

    <el-button type="primary" @click="openAddDialog">+ 新增员工</el-button>
    <el-button type="danger" @click="batchDelete">- 批量删除</el-button>

    <!-----------------------页面主体的数据列表-------------------------------->
    <el-table :data="empList" border style="width: 100%; margin-top:10px" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" />
        <el-table-column prop="name" label="姓名" width="130" align="center" />
        <el-table-column prop="gender" label="性别" width="100" align="center">
            <template #default="scope">
                <span v-if="scope.row.gender == 1">男</span>
                <span v-else-if="scope.row.gender == 2">女</span>
                <span v-else>其他</span>
            </template>
        </el-table-column>
        <el-table-column prop="image" label="头像" width="180" align="center">
            <template #default="scope">
                <img :src="scope.row.image" width="50px" />
            </template>
        </el-table-column>
        <el-table-column prop="deptName" label="所属部门" width="180" align="center" />
        <el-table-column prop="job" label="职位" width="100" align="center">
            <template #default="scope">
                <span v-if="scope.row.job == 1">班主任</span>
                <span v-else-if="scope.row.job == 2">讲师</span>
                <span v-else>其他</span>
            </template>
        </el-table-column>
        <el-table-column prop="entryDate" label="入职时间" width="130" align="center" />
        <el-table-column prop="updateTime" label="最后修改时间" width="180" align="center" />
        <el-table-column label="操作" align="center">
            <template #default="scope">
                <el-button size="small" type="primary" @click="handleEdit(scope.$index, scope.row)">
                    编辑
                </el-button>
                <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!----------------------------------分页组件---------------------------------------->
    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="margin-top:10px" />
    <!----------------------------------dialog弹框-------------------------------------->
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="700" @close="dialogClose">
        <el-form :model="insertOrUpdateForm" ref="dialogFromRef" :rules="rules">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
                        <el-input v-model="insertOrUpdateForm.username" autocomplete="off" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="姓名" :label-width="formLabelWidth" class="required-label" prop="name">
                        <el-input v-model="insertOrUpdateForm.name" autocomplete="off" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="性别" :label-width="formLabelWidth" required prop="gender">
                        <el-select v-model="insertOrUpdateForm.gender" placeholder="请选择" clearable style="width: 100%">
                            <el-option label="男" value="1" />
                            <el-option label="女" value="2" />
                            <el-option label="其他" value="3" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="手机号" :label-width="formLabelWidth" class="required-label" prop="phone">
                        <el-input v-model="insertOrUpdateForm.phone" autocomplete="off" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="薪资" :label-width="formLabelWidth" prop="salary">
                        <el-input v-model="insertOrUpdateForm.salary" autocomplete="off" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="入职日期" :label-width="formLabelWidth" style="width:100%">
                        <el-date-picker style="width:100%" v-model="insertOrUpdateForm.entryDate" type="date"
                            value-format="YYYY-MM-DD" placeholder="选择入职日期" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="所属部门" :label-width="formLabelWidth">
                        <el-select v-model="insertOrUpdateForm.deptId" placeholder="请选择" style="width: 100%">
                            <el-option :label="dept.name" :value="dept.id" v-for="(dept, index) in deptList"
                                :key="dept.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="职位" :label-width="formLabelWidth">
                        <el-select v-model="insertOrUpdateForm.job" placeholder="请选择" style="width: 100%">
                            <el-option :label="job.name" :value="job.id" v-for="(job, index) in jobList"
                                :key="job.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="头像" :label-width="formLabelWidth">
                        <el-upload :headers="{ 'token': loginInfo.token }" class="avatar-uploader" action="/api/upload"
                            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                            <img v-if="insertOrUpdateForm.image" :src="insertOrUpdateForm.image" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row>
                <el-col :span="24">
                    <el-form-item label="工作经历" :label-width="formLabelWidth">
                        <el-button type="success" size="small" @click="addExpr">+ 添加工作经历</el-button>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="10" v-for="(expr, index) in insertOrUpdateForm.exprList">
                <el-col :span="10">
                    <el-form-item label="时间" style="padding-left:20px" size="small">
                        <el-date-picker value-format="YYYY-MM-DD" type="daterange" range-separator="至"
                            start-placeholder="开始时间" end-placeholder="结束时间" v-model="expr.exprDate" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="公司" size="small">
                        <el-input autocomplete="off" v-model="expr.company" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="职位" size="small">
                        <el-input autocomplete="off" v-model="expr.job" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-form-item size="small">
                        <el-button type="danger" @click="deleteExpr(expr)">- 删除</el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="insertOrUpdate(dialogFromRef)">保存</el-button>
            </div>
        </template>
    </el-dialog>


</template>

<style scope>
.title {
    font-size: 20px;
    font-weight: 600;
}

.demo-form-inline {
    margin-top: 10px
}

.required-label .el-form-item__label:before {
    content: '*';
    color: red;
    margin-right: 2px;
}

.avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}
</style>